package com.us.proframe.controller;

import com.alibaba.fastjson.JSONObject;
import com.us.proframe.model.knowledge.SysUser;
import com.us.proframe.service.knowledge.SysUserService;
import com.us.proframe.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.UUID;

/**
 * 处理注册相关的控制逻辑.
 * User: lyh
 * Date: 2017/8/9
 * Time: 15:32
 */
@Controller
@RequestMapping("/register")
public class RegisterController {

    private final static Logger LOGGER = LoggerFactory.getLogger(RegisterController.class);


    /**
     * 跳转到注册页面
     * */
    @RequestMapping("/toregister")
    public Object toRegister(){
        LOGGER.info("注册页面跳转");
        return "business/register";
    }

    @Autowired
    private SysUserService sysUserService;

    /**
     * 处理注册业务
     * */
    @RequestMapping("/doregister")
    public Object doRegister(@Valid SysUser sysUser, BindingResult result, HttpServletRequest request, HttpServletResponse response){
        LOGGER.info("注册业务处理，请求参数：{}", JSONObject.toJSONString(sysUser));
        if(result.hasErrors()){
            request.setAttribute("result",JSONObject.toJSONString(ResultUtil.error(-1,"用户名已存在,不可用！")));
            return  "exception/exception";
        }
        //校验用户名是否存在
        if(checkUserByName(sysUser.getUsername())){
            LOGGER.info("该用户名已注册！用户注册信息：{}",sysUser);
        }else{
            sysUser.setSalt(UUID.fromString(sysUser.getUsername()).toString());
            sysUserService.insert(sysUser);
            LOGGER.info("用户注册成功！用户注册信息：{}",sysUser);
        }
        return "business/login";

    }
    /**
     * 校验用户
     * */
    @RequestMapping("/checkuserName")
    @ResponseBody
    public Object checkUserName(@RequestParam(value = "username",required = true)String userName){
        LOGGER.info("校验用户名是否存在，请求参数：{}", userName);
        if(checkUserByName(userName)){
            LOGGER.info("用户名已经存在");
            return ResultUtil.error(10002,"用户名已存在");
            //TODO 存在的处理逻辑
        }else{
            LOGGER.info("用户名不存");
            //TODO 用户名不存在的业务逻辑处理
            return ResultUtil.success();
        }

    }


    private boolean checkUserByName(String userName){
        SysUser user = sysUserService.findByUserName(userName);
        if(user != null){
           return true;
        }
        return false;
    }
}
